import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { fetchValidation } from '@/utils';

import { queryImpoowerList, queryBindCabinetList } from './service';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchBindCabinet: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'tencentOverview',

  state: {
    dataInfo: {
      list: [],
      count: 0,
    },
    bindCabinetList: {
      list: [],
      count: 0,
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryImpoowerList, payload);
      const data = fetchValidation(response);

      yield data &&
        put({
          type: 'save',
          payload: { dataInfo: data.body },
        });
    },

    *fetchBindCabinet({ payload }, { call, put }) {
      const response = yield call(queryBindCabinetList, payload);
      const data = fetchValidation(response);

      yield data &&
        put({
          type: 'save',
          payload: { bindCabinetList: data.body },
        });
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default Model;
